/*
 * @Author: 橘子
 * @Date: 2023/7/9
 * @Project_description: index
 * @Description: 代码是我抄的，不会也是真的
 */

const qiniuUpload = require('./upload.cicd')

const qiniuDelete = require('./delete.cicd')
const qiniuRefresh = require('./refresh.cicd')
'use strict'
const config = require('./config.cicd')
const fs = require('fs')
/**
 * @Description: 递归读取目录下的所有文件
 * @author 橘子
 * @date 2023-06-27
 */
const readDirDepthFileSync = (path, suffix = false, dirList = []) => {
	// 读取目录
	const pa = fs.readdirSync(path)
	pa.forEach((ele, index) => {
		const info = fs.statSync(`${path}/${ele}`)
		if (info.isDirectory()) {
			readDirDepthFileSync(`${path}/${ele}`, suffix, dirList)
		} else {
			if (suffix) {
				dirList.push(`${ele}`)
			} else {
				dirList.push(`${path}/${ele}`)
			}

		}
	})
	return dirList
}


const newTiem = () => {
	return new Date().getTime()
}


const install = async () => {
	if (config.isDelete) {
		console.log('开始删除文件:')
		//获取当前时间
		const nowTime0 = newTiem()
		//删除目录
		await qiniuDelete.install()
		console.log(`删除完成:耗时${newTiem() - nowTime0}ms`)
	}

	console.log(`开始上传:`)
	//获取当前时间
	const nowTime1 = newTiem()
	//读取目录
	const buildFileList = readDirDepthFileSync(config.buildPath)
	console.log('文件数:', buildFileList.length)
	let res = await qiniuUpload.uploadList(buildFileList)
	if (res[0]) {
		console.log('重新上传')
		await qiniuUpload.uploadList(res)
	}
	console.log(`上传完成:耗时${newTiem() - nowTime1}ms`)
	//刷新缓存
	console.log(`开始刷新缓存:`)
	//获取当前时间
	const nowTime2 = newTiem()
	// 获取需要刷新的路径
	const refreshUrl = config.scopePath ? config.refreshUrl + config.scopePath : config.refreshUrl
	await qiniuRefresh.refreshUrl([refreshUrl + 'index.html'])
	// await qiniuRefresh.prefetchUrl([refreshUrl])
	await qiniuRefresh.prefetchUrl([refreshUrl + 'index.html'])
	if (config.isRefreshDir) await qiniuRefresh.refreshDir([refreshUrl])
	console.log(`刷新缓存完成:耗时${newTiem() - nowTime2}ms`)
	console.log(`访问地址${refreshUrl + 'index.html'}`)
}

install().then(r => {})